<?php
class controller_pic extends controller_abstract
{
	function __construct(& $app)
	{
		parent::__construct($app);
	}

	function index()
	{
		@set_time_limit(0);
		ob_end_flush();
		ini_set('output_buffering', 0);
		if($this->is_post() && $_POST['url'])
		{
			$file = file_get_contents($_POST['url']);
			preg_match_all('/<img\s+[^>]*src\s*=\s*(["\']?)([^>"\']+)\1[^>]*[\/]?>/isU',$file,$matches);
			//print_r($matches);exit;
			if(!empty($matches[2]))
			{
				$start = 0;
				$end = count($matches[2]);
				if($_POST['offset'])
				{ 
					$offset = explode('-',$_POST['offset']);
					$start = $offset[0]-1;
					$end = $offset[1]; 
				}
				if(!is_dir($_POST['picpath']))
				{
					$this->error = '给定的目录不存在！';
					exit($this->error());
				}
				$time = time();
				for($i=$start; $i<$end ; $i++)
				{
					$fileext = fileext($matches[2][$i])?fileext($matches[2][$i]):'jpg';
					$filename = $_POST['picpath'].$time.'_'.$i.'.'.$fileext;
					$result = @copy($matches[2][$i], $filename);
					echo '第'.$i.'张采集'.($result?'成功':'失败').'！<br />';
					flush();
				}
				echo '<a href="'.url('pic/pic/index', false).'">继续采集</a>';
			}
		}
		else
		{
			$this->view->assign('header','获取此页图片');
			$this->view->display('fetch_page');
		}
	
	}

	function imgurl()
	{
		if($this->is_post())
		{
			@set_time_limit(0);
			$file = file_get_contents($_POST['url']);
			preg_match_all('/<img\s+[^>]*src\s*=\s*(["\']?)([^>"\']+)\1[^>]*[\/]?>/isU',$file,$matches);
			if(!empty($matches[2]))
			{
				$start = 0;
				$end = count($matches[2]);
				$result = array();
				if($_POST['offset'])
				{ 
					if(strpos($_POST['offset'],','))
					{
						$keys = explode(',', $_POST['offset']);
						foreach ($matches[2] as $k => $v)
						{
							if(in_array($k+1,$keys)) $result[] = $v;
						}
						echo $this->json->encode($result);
						exit;
					}
					else 
					{
						$offset = explode('-',$_POST['offset']);
						$start = intval($offset[0])-1;
						$end = intval($offset[1])-1;
					}
				}
				$result = array_slice($matches[2],$start,$end);
			}
			echo $this->json->encode($result);
		}
		else 
		{
			$this->showmessage('您不该来这里！','back');
		}
	}
}